package com.entrogy.controller;

import com.entrogy.api.ThdidPersonApi;
import com.entrogy.bean.*;
import com.entrogy.config.Result;
import com.entrogy.dao.WeixinMapper;
import com.entrogy.service.*;
import com.entrogy.timing.ChangePersonTimeThread;
import com.entrogy.timing.TimingTaskService;
import com.entrogy.utils.*;
import com.entrogy.utils.constants.Constants;
import com.entrogy.utils.constants.ErrorEnum;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用户的相关操作
 * @author xlr
 * @date 2019-1
 */
@RestController
@RequestMapping("/user")
@Api(description = "用户登录接口")
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	@Value("${image.storage.host}")
	private String imageHost;
	@Value("${image.storage.port}")
	private String hostPort;
	@Value("${show.image.url}")
	private String showImage;
	@Autowired
	private UserService userService;
	@Autowired
	private THDio thdio;
	@Autowired
    private CourseService courseService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private ParentService parentService;
	@Autowired
	private SchoolService schoolService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private PositionService positionService;
	@Autowired
	private WeixinService weixinService;
	@Autowired
	private WeixinMapper weixinMapper;
	@Autowired
	private ThdidPersonApi thdidPersonApi;

	@RequestMapping(value = "/userlogin",method = RequestMethod.POST)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "phone", value = "用户名", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "roleId", value = "用户选择的角色id", dataType = "Integer", paramType = "query"),
	})
	public Map<String, Object> userLogin(String phone,String password,Integer roleId) {
		if (roleId == null){
			//根据电话号码先判断是否存在
			UserEntity userEntity = userService.getUserByMobile(phone);
			if (null == userEntity || userEntity.getDeleteStatus().equals(1)) {
				return ApiReturnUtil.error("对不起，用户不存在，请您前去注册。");
			}
			//查询出该用户的所有的角色判断是否是多角色用户，如果是多用户角色，返回让其选择角色然后再次登录,单角色用户直接登录
			List<Role> roles = roleService.findRolesByUsername(phone);
			if(roles.size() > 1){
				Map<String, Object> map = new HashMap<>();
				map.put("roles",roles);
				return ApiReturnUtil.success("获取角色列表成功",map);
			}else {
				return userService.login(phone, password, roles.get(0));
			}
		}else {
			Role role = roleService.findRoleByRoleId(roleId);
			return userService.login(phone, password, role);
		}
	}

	@ApiOperation(value = "name,mobile,photo,sex只需这几个字段 作为 post请求参数")
	@RequestMapping(value = "/insertuser",method = RequestMethod.POST)
//	@RequiresPermissions("user:add")
	public Map<String, Object> insertUser(@ModelAttribute EditUserEntity userEntity){
		// 插入用户之前首先判断该手机号是否已经注册
		String mobile = userEntity.getMobile();
		UserEntity tempUser = userService.getUserByMobile(mobile);
		if (tempUser != null){
			Map<String, Object> map = new HashMap<>();
			map.put("code",ErrorEnum.E_103.getErrorCode());
			map.put("msg",ErrorEnum.E_103.getErrorMsg());
			return map;
		}
		if (!StringUtils.isNoneBlank(userEntity.getGradeId())){
			userEntity.setGradeId("0");
		}
		if (!StringUtils.isNoneBlank(userEntity.getClassId())){
			userEntity.setClassId("0");
		}
		// 如果职位不是班主任的话，那么grade_id和class_id都为0
		boolean isNotClassLeader = true;
		boolean isNotGradeLeader = true;
		List<Integer> positionIdList = userEntity.getPositionIdList();
		// 超级管理员新建用户，需要一个默认职位，暂定教务处主任
		Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
		if (positionIdList == null){
			if (schoolCode != null && schoolCode.equals(1)){
				positionIdList = new ArrayList<>();
				positionIdList.add(2);
			}
		}
		if (positionIdList.contains(16)){
			isNotClassLeader = false;
		}
		if (positionIdList.contains(15)){
			isNotGradeLeader = false;
		}
		if (isNotClassLeader){
			userEntity.setClassId("9999");
		}
		if (isNotGradeLeader && isNotClassLeader){
			userEntity.setGradeId("9999");
		}

		// 如果在新增班主任，那么需要判断他现在设置的班级有没有班主任，如果有，则返回让其修改（现在暂时只支持一个班一个班主任）
		if (!isNotClassLeader){
			TeacherBasicInfoEntity classLeaderTeacher = positionService.getClassLeader(Integer.valueOf(userEntity.getClassId()), userEntity.getSchoolCode());
			if (classLeaderTeacher != null){
				Map<String, Object> map = new HashMap<>();
				map.put("code",ErrorEnum.E_101.getErrorCode());
				map.put("msg","对不起，该班级已经有班主任，不能再次分配，请更换班级！");
				return map;
			}
		}
		// 如果在新增年级组长，那么需要判断他现在设置的班级有没有年级组长，如果有，则返回让其修改（现在暂时只支持一个年级一个年级组长）
		if (!isNotGradeLeader){
			TeacherBasicInfoEntity gradeLeaderTeacher = positionService.getGradeLeader(Integer.valueOf(userEntity.getGradeId()), userEntity.getSchoolCode());
			if (gradeLeaderTeacher != null){
				Map<String, Object> map = new HashMap<>();
				map.put("code",ErrorEnum.E_101.getErrorCode());
				map.put("msg","对不起，该班级已经有年级组长，不能再次分配，请更换班级！");
				return map;
			}
		}
		// 生成用户的id
		String uid = "1"+System.currentTimeMillis();
		userEntity.setId(uid);
		// 前端没填性别的话，设置为默认值
		Integer sex = userEntity.getSex();
		if (sex == null || "".equals(sex) ){
			userEntity.setSex(1);
		}
		// 一定要先在我们库里添加人员，然后再推送到实义德，这样推送完成后，才能更新我们库里人员的实义德id
		boolean result = userService.insertUser(userEntity);
		TeacherBasicInfoEntity teacher = new TeacherBasicInfoEntity();
		teacher.setIcNumber(userEntity.getIcNumber())
				.setTeacherName(userEntity.getName())
				.setPhoto(userEntity.getPhoto())
				.setGender(userEntity.getSex())
				.setIdNumber(userEntity.getIdNumber())
				.setTeacherId(userEntity.getId());
		thdidPersonApi.addTeacherToAll(teacher, schoolCode);
		if(result){
			return ApiReturnUtil.success("添加老师成功",null);
		}else {
			return ApiReturnUtil.error("添加老师失败");
		}
	}

	@ApiOperation(value = "查找用户，带有参数的话可以实现模糊查询")
	@RequestMapping(value = "/findUsers",method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "teacherName", value = "老师姓名", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "mobile", value = "老师手机号", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "currentPage",  value = "当前页数", dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize",  value = "页数数据条数", dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "schoolCode",  value = "学校Id", dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "teacherId",  value = "教师id", dataType = "String", paramType = "query"),
	})
//	@RequiresPermissions("user:list")
	public Msg findUsers(String teacherName, String mobile, Integer currentPage, Integer pageSize,Integer schoolCode, String teacherId) {
		if (currentPage == null){
			//前端没有当前页的参数，默认为1
			currentPage = 1;
		}
		if (pageSize == null){
			pageSize = 10;
		}
		int totalCount = userService.countUser(schoolCode, teacherName);
		PageHelper.startPage(currentPage,pageSize);
		List<UserEntity> users = userService.findUsersRowBound(teacherName, mobile, schoolCode, teacherId);
		Map<String, Object> pageInfo = new HashMap<>();
		pageInfo.put("totalCount", totalCount);
		pageInfo.put("users", users);
		pageInfo.put("baseImage",showImage);
		return Msg.success().add("pageInfo",pageInfo);
	}

	@ApiOperation(value = "小程序端教师查看自己的个人信息")
	@RequestMapping(value = "/getTeacherInformation",method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "teacherId",  value = "教师id", required = true, dataType = "String", paramType = "query"),
	})
	public Msg getTeacherInformation(String teacherId) {
		if (!StringUtils.isNoneBlank(teacherId)){
			teacherId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
		}
		TeacherDetailInfoEntity teacherInformation = userService.getTeacherDetailInfo(teacherId);
		return Msg.success().add("teacherInformation",teacherInformation).add("showImage", showImage);
	}

	@ApiOperation(value = "小程序端管理员查看某个教师的信息")
	@RequestMapping(value = "/teacher-info-admin",method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "uid",  value = "管理员id", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "teacherId",  value = "教师id", required = true, dataType = "String", paramType = "query"),
	})
	public Msg getTeacherInformation(String uid, String teacherId) {
		TeacherDetailInfoEntity teacherInformation = userService.getTeacherDetailInfo(teacherId);
		return Msg.success().add("teacherInformation",teacherInformation).add("showImage", showImage);
	}

	@ApiOperation(value = "更新user的信息")
	@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
//	@RequiresPermissions("user:update")
	public Map<String,Object> updateUser(EditUserEntity userEntity){
		// 判断修改的号码是否是在系统中已存在的
		// 比对电话号码是否已更改
		UserEntity userEntityDb = userService.getUserByUid(userEntity.getId());
		if (!userEntity.getMobile().equals(userEntityDb.getMobile())){
			UserEntity tempUser = userService.getUserByMobile(userEntity.getMobile());
			if (tempUser != null) {
				Map<String, Object> map = new HashMap<>();
				map.put("code",ErrorEnum.E_103.getErrorCode());
				map.put("msg",ErrorEnum.E_103.getErrorMsg());
				return map;
			}
			// 如果pc端更改了电话号码，那么需要将原来的电话号码和微信号解绑
			boolean result = userService.cancelWeiXinAndPhoneBind(userEntity.getMobile());
			logger.info("用户：" + userEntity.getName() + "更改了电话号码，并且微信解绑" + (result == true ? "成功！" : "失败！"));
		}

		// 如果职位不是班主任的话，那么grade_id和class_id都为0
        boolean isNotClassLeader = true;
        boolean isNotGradeLeader = true;
        List<Integer> positionIdList = userEntity.getPositionIdList();
        if (positionIdList.contains(16)){
            isNotClassLeader = false;
        }
        if (positionIdList.contains(15)){
            isNotGradeLeader = false;
        }
        if (isNotClassLeader){
            userEntity.setClassId("9999");
        }
        if (isNotGradeLeader && isNotClassLeader){
            userEntity.setGradeId("9999");
        }

        // 如果在新增班主任，那么需要判断他现在设置的班级有没有班主任，如果有，则返回让其修改（现在暂时只支持一个班一个班主任）
		if (!isNotClassLeader){
			TeacherBasicInfoEntity classLeaderTeacher = positionService.getClassLeader(Integer.valueOf(userEntity.getClassId()), userEntity.getSchoolCode());
			if (classLeaderTeacher != null){
				if (StringUtils.isNoneBlank(classLeaderTeacher.getTeacherId()) && !userEntity.getId().equals(classLeaderTeacher.getTeacherId())){
					Map<String, Object> map = new HashMap<>();
					map.put("code",ErrorEnum.E_101.getErrorCode());
					map.put("msg","对不起，该班级已经有班主任，不能再次分配，请更换班级！");
					return map;
				}
			}
		}
		// 如果在申请/修改年级组长，那么需要判断他现在设置的班级有没有年级组长，如果有，则返回让其修改（现在暂时只支持一个年级一个年级组长）
		if (!isNotGradeLeader){
			TeacherBasicInfoEntity gradeLeaderTeacher = positionService.getGradeLeader(Integer.valueOf(userEntity.getGradeId()), userEntity.getSchoolCode());
			if (gradeLeaderTeacher != null){
				if (StringUtils.isNoneBlank(gradeLeaderTeacher.getTeacherId()) && !gradeLeaderTeacher.getTeacherId().equals(userEntity.getId())){
					Map<String, Object> map = new HashMap<>();
					map.put("code",ErrorEnum.E_101.getErrorCode());
					map.put("msg","对不起，该班级已经有年级组长，不能再次分配，请更换班级！");
					return map;
				}
			}

		}
		// 修改实义德后台的教师信息
		if(StringUtils.isNoneBlank(userEntity.getPhoto()) || StringUtils.isNoneBlank(userEntity.getName())){
			TeacherBasicInfoEntity teacher = new TeacherBasicInfoEntity();
			teacher.setTeacherName(userEntity.getName()).setPhoto(userEntity.getPhoto()).setTeacherId(userEntity.getId());
			thdidPersonApi.updateTeacherToAll(teacher, userEntityDb.getSchoolCode());
		}
		boolean result = userService.updateUser(userEntity);
		if (result){
			return ApiReturnUtil.success("用户信息更新成功","");
		}else {
			return ApiReturnUtil.error("用户信息更新失败");
		}
	}

	@ApiOperation(value = "更新user的信息，小程序接口")
	@RequestMapping(value = "/updateUserFromWeApp",method = RequestMethod.POST)
	public Map<String,Object> updateUserFromWeApp(String id, String name, String mobile, String photo, Integer verifyCodeId, Integer verifyCode, Integer winXinInfoId){
		Integer schoolCode = userService.getSchoolCodeByUserId(id);
		if (verifyCode != null && verifyCodeId != null){
			boolean compareVerifyCode = parentService.compareVerifyCode(verifyCodeId, verifyCode);
			if (!compareVerifyCode){
				return ApiReturnUtil.error("对不起，验证码错误！");
			}
		}
		EditUserEntity userEntity = new EditUserEntity();
		// 垃圾json不能put值为null的key
		userEntity.setName(name == null ? userService.getUserByUid(id).getName() : name);
		userEntity.setMobile(mobile);
		// 如果手机号码有变化，那么解除关联
		if (!StrUtils.isNullOrEmpty(mobile)){
			boolean result = parentService.weiXinBindNewPhone(winXinInfoId, mobile);
			if(result){
				return ApiReturnUtil.error("微信号和手机号码解绑失败！");
			}
		}
		userEntity.setPhoto(photo);
		userEntity.setId(id);
		if(StringUtils.isNoneBlank(userEntity.getPhoto()) || StringUtils.isNoneBlank(name)){
			TeacherBasicInfoEntity teacher = new TeacherBasicInfoEntity();
			teacher.setTeacherName(userEntity.getName()).setPhoto(userEntity.getPhoto()).setTeacherId(userEntity.getId());
			thdidPersonApi.updateTeacherToAll(teacher, schoolCode);
		}
		boolean result = userService.updateUser(userEntity);
		if (result){
			return ApiReturnUtil.success("用户信息更新成功","");
		}else {
			return ApiReturnUtil.error("用户信息更新失败");
		}
	}

	// 2019-11-28 luoxingjiang 修改用户删除为软删除
	@ApiOperation(value = "删除用户信息")
	@RequestMapping(value = "/deleteUser",method = RequestMethod.POST)
//	@RequiresPermissions("user:delete")
	public Msg deleteUser(String id) {
        userService.deleteUser(id);
        return Msg.success();
	}

	@ApiOperation(value = "获取所有教师的所教科目")
	@RequestMapping(value = "/getuseraccount",method = RequestMethod.GET)
	public Map<String,Object>  getUserAccount(String schoolCode){
		List<UserEntity> userEntities = courseService.getUserAccount(schoolCode);
        return ApiReturnUtil.success("获取成功",userEntities);
	}


	@ApiOperation(value = "给老师分配科目,一个老师可以带多个班的多个科目,也可以一个班的同一个科目被两个老师教")
	@RequestMapping(value = "/accountassignment",method = RequestMethod.POST)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "courseId",value = "科目ID",paramType = "query",dataType = "String",required = true),
			@ApiImplicitParam(name = "teacherId",value = "教师ID",paramType = "query",dataType = "String",required = true),
			@ApiImplicitParam(name = "schoolCode",value = "学校ID",paramType = "query",dataType = "int",required = true)
	})
	public Map<String,Object>  accountAssignment(String[] courseId,String teacherId,String schoolCode,int  type){
		String courseIds=getStiringCourseId(courseId);
		if (courseIds.substring(courseIds.length()-2,courseIds.length()-1).equals(",")){
			courseIds=courseIds.substring(0,courseIds.length()-2);
		}
		int code = courseService.accountAssignment(courseIds.split(","),teacherId,schoolCode,type);
		if(code == 1){
			return ApiReturnUtil.success("分配科目成功","");
		}
        return ApiReturnUtil.error("对不起,网络异常");
	}

	@ApiOperation(value = "编辑老师的所教课程")
	@RequestMapping(value = "/updateuseraccount",method = RequestMethod.POST)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "courseId",value = "科目ID",paramType = "query",dataType = "String",required = true),
			@ApiImplicitParam(name = "teacherId",value = "教师ID",paramType = "query",dataType = "String",required = true),
			@ApiImplicitParam(name = "schoolCode",value = "学校ID",paramType = "query",dataType = "int",required = true)
	})
	public Map<String,Object> updateUserAccount(String[] courseId,String teacherId,String schoolCode){
		String courseIds=getStiringCourseId(courseId);
		int code = courseService.updateUserAccount(courseIds,teacherId,schoolCode);
		if(code == 1){
			return ApiReturnUtil.success("编辑科目成功","");
		}
		return ApiReturnUtil.error("对不起,网络异常");
	}

    @ApiOperation(value = "班主任获取所在班级的所有学生")
	@ApiImplicitParam(value = "教师ID",name = "uid",dataType = "String",paramType = "query",required = true)
	@RequestMapping(value = "/getstudents",method = RequestMethod.GET)
	public Map<String,Object> getStudentsByBanzhuren(String uid){
		UserEntity userEntity = userService.getUserByUid(uid);//获取学校ID
		boolean isClassLeader = positionService.checkPosition(uid, 16);
		if (!isClassLeader){
			return ApiReturnUtil.error("对不起,您没有权限");
		}
		List<StudentEntity> lists = userService.getStudentsByBanzhu(uid, userEntity.getSchoolCode());
		if(lists.size()>0){
			return ApiReturnUtil.success("查询成功",lists);
		}
       return ApiReturnUtil.error("对不起,您没有权限哟");
	}

	private  String  getStiringCourseId(String[] courseId){
		String courseIds = "";
		for (int i = 0;i < courseId.length;i++){
			if (courseId[i].indexOf("[")!=-1){
				courseId[i]=courseId[i].substring(1,courseId[i].length());
			}
			if(courseId[i].indexOf("]")!=-1){
				courseId[i]=courseId[i].substring(0,courseId[i].length()-1);
			}
			if(courseId.length==1){
				courseIds=courseId[i];
			}else{
				courseIds+=courseId[i]+",";
			}
		}
		return  courseIds;
	}

	@ApiOperation(value = "德育处获取班主任的离校设置状态 看那些人没有设置")
	@RequestMapping(value = "getleaveschool",method = RequestMethod.GET)
	public Map<String,Object> getLeaveSchool(String uid){
		Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		List<LeaveSchoolSetEntity> lists = userService.getLeaveSchool(schoolCode);
		for (LeaveSchoolSetEntity list : lists) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Long dateDB = null;
			try {
				String updateTime = list.getUpdateTime();
				if (updateTime == null){
					list.setIsSet("未更新");
					continue;
				}
				dateDB = simpleDateFormat.parse(list.getUpdateTime()).getTime();
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if (IsThisWeekUtil.isThisWeek(dateDB)) {
				list.setIsSet("已更新");
			} else {
				list.setIsSet("未更新");
			}
		}
		return ApiReturnUtil.success("查询成功",lists);
	}


	@ApiOperation(value = "小程序获取该校所有教职员工作为通讯录显示")
	@ApiImplicitParam(value = "用户id",name = "uid",dataType = "String",paramType = "query",required = true)
	@GetMapping(value = "listSchoolAllUser")
	public Msg listSchoolAllUser(String uid){
		Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		List<com.alibaba.fastjson.JSONObject> teacherList = userService.listSchoolAllUser(schoolCode);
		return Msg.success().add("teacherList", teacherList).add("showImage", showImage);
	}

	@ApiOperation(value = "pc端教师通过旧密码修改密码")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "newPassword",value = "新密码",paramType = "query",dataType = "String",required = true),
			@ApiImplicitParam(name = "oldPassword",value = "旧密码",paramType = "query",dataType = "String",required = true),
	})
	@PostMapping(value = "changePassword")
	public Msg changePassword(String newPassword, String oldPassword){
		if (!StringUtils.isNoneBlank(newPassword) || !StringUtils.isNoneBlank(oldPassword)){
			return Msg.fail(ErrorEnum.E_101, "对不起，您提交的信息有误！");
		}
		//校验新密码格式（长度为6-12个字符,并且由字母和数字组成，字母区分大小写）
		String pattern = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$";
		String realPassword = AESUtil.decrypt(newPassword);
		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(realPassword);
		if (!m.matches()){
			return Msg.fail(ErrorEnum.E_101, "对不起，密码格式不正确，长度为6-12个字符,并且由字母和数字组成，字母区分大小写！");
		}
		//判断旧密码是否正确
		String userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
		UserEntity userEntity = userService.getUserByUid(userId);
		if (!userEntity.getPassword().equals(oldPassword)){
			return Msg.fail(ErrorEnum.E_101, "对不起，您的旧密码不正确，请重试！");
		}
		boolean setPasswordSuccess = userService.updateUserPassword(userId, newPassword);
		if (setPasswordSuccess){
			return Msg.success();
		}
		return Msg.fail(ErrorEnum.E_101, "密码设置失败，请联系管理员！");
	}

	@ApiOperation(value = "登录超时返回状态码，系统使用shiro管理session，当session过期时，那么会访问index.jsp(ShiroConfiguration中设置)")
	@GetMapping(value = "index.jsp")
	public Msg redirectToLogin(){
		return Msg.fail(ErrorEnum.E_20011, ErrorEnum.E_20011.getErrorMsg());
	}

	/**
	 *   给教师分配课程
	 *
	 * @return
	 */
    @PostMapping("/distributionByUser")
	public Result<UserEntity>   distributionByUser(@RequestParam(value="id")String id,@RequestParam(value="course_id")String course_id){
    	int a=userService.UpdateDistributionByUser(course_id,id);
      if (a==1){
	 	return new Result<UserEntity>().getResult(1,"分配成功",1,"");
	  }
    	return new Result<UserEntity>().getResult(0,"分配失败",0,"");
	}

    @PostMapping("/teacher-info-change-apply")
	@ApiOperation(value = "教师信息修改/注册提交审核")
	public Msg teacherInfoChangeApply(@RequestBody TeacherInformationChangeEntity teacherInformationChange){

		Integer schoolCode = teacherInformationChange.getSchoolCode();
		String applyUserId = teacherInformationChange.getApplyUserId();

		// 查询该申请人或者申请的电话号码是否有处于审核中的记录
		Integer changeId = userService.getTeacherInfoChangeRecord(teacherInformationChange.getApplyUserId(), teacherInformationChange.getNewPhone());
		if (changeId != null){
			return Msg.fail(ErrorEnum.E_101, "对不起，您已经有一条信息变更记录在待审核状态，请联系管理员审核后再次提交，谢谢！");
		}

		// 判断号码是否已存在
    	String phone = teacherInformationChange.getNewPhone();
    	if (StringUtils.isNoneBlank(phone)){
			UserEntity userEntity = userService.getUserByMobile(phone);
			if (userEntity != null){
				return Msg.fail(ErrorEnum.E_103, ErrorEnum.E_103.getErrorMsg());
			}
		}

		// 如果在新增/修改班主任，那么需要判断他现在设置的班级有没有班主任，如果有，则返回让其修改（现在暂时只支持一个班一个班主任）
		List<TeacherAdvancedInfoChangeEntity> teacherAdvancedInfoChangeList = teacherInformationChange.getTeacherAdvancedInfoChangeList();
    	boolean isUpdateClassId = false;
    	Integer gradeId = 0;
    	Integer classId = 0;
		for (TeacherAdvancedInfoChangeEntity teacherAdvancedInfoChange : teacherAdvancedInfoChangeList) {
			if (teacherAdvancedInfoChange.getNewPositionSid() == 16){
				// 当前变更记录所指定的班主任
				isUpdateClassId = true;
				gradeId = teacherAdvancedInfoChange.getNewGradeId();
				classId = teacherAdvancedInfoChange.getNewClassId();
			}
		}
		if (isUpdateClassId){
			TeacherBasicInfoEntity classLeaderTeacher = positionService.getClassLeader(classId, schoolCode);
			if (classLeaderTeacher != null){
				if (StringUtils.isNoneBlank(classLeaderTeacher.getTeacherId()) && !classLeaderTeacher.getTeacherId().equals(applyUserId)){
					return Msg.fail(ErrorEnum.E_101, "对不起，该班级已经有班主任，不能再次新增，请更换班级！");
				}
			}
		}

		// 如果在申请/修改年级组长，那么需要判断他现在设置的班级有没有年级组长，如果有，则返回让其修改（现在暂时只支持一个年级一个年级组长）
		boolean isUpdateGradeId = false;
		for (TeacherAdvancedInfoChangeEntity teacherAdvancedInfoChange : teacherAdvancedInfoChangeList) {
			if (teacherAdvancedInfoChange.getNewPositionSid() == 15){
				// 当前变更记录所指定的年级组长
				isUpdateGradeId = true;
				gradeId = teacherAdvancedInfoChange.getNewGradeId();
			}
		}

		if (isUpdateGradeId){
			TeacherBasicInfoEntity gradeLeaderTeacher = positionService.getGradeLeader(gradeId, schoolCode);
			if (gradeLeaderTeacher != null && !gradeLeaderTeacher.getTeacherId().equals(applyUserId)){
				if (StringUtils.isNoneBlank(gradeLeaderTeacher.getTeacherId()) && !gradeLeaderTeacher.getTeacherId().equals(applyUserId)){
					return Msg.fail(ErrorEnum.E_101, "对不起，该年级已经有年级组长，不能再次新增，请更换年级！");
				}
			}
		}

        // 教师注册审核的权限码
        String permissionCode = "teacher-register:audit";
        // 查找有教师注册审核权限的人员id
        List<UserEntity> auditUserList = userService.listHasSomePermissionUserIdList(schoolCode, permissionCode);
        if (auditUserList.size() == 0){
            return Msg.fail(ErrorEnum.E_101, "对不起，您的学校没有信息审核人员，请联系学校管理员！");
        }
        boolean result = userService.insertUserInfoChangeApply(teacherInformationChange);
        if (result){
            // 拼接通知内容需要根据变更类型
            String changeType = teacherInformationChange.getChangeType() == 0 ? "信息修改" : "注册";
            String teacherName = teacherInformationChange.getChangeType() == 0 ? userService.getUserByUid(teacherInformationChange.getApplyUserId()).getName() : teacherInformationChange.getNewName();
            for (UserEntity userEntity : auditUserList) {
                String userPhone = userEntity.getMobile();
                // 公众号通知审核人员审核信息
                PubCountEntity pubCountEntity = messageService.getPubCountOpenidByPhone(userPhone);
                if (pubCountEntity == null){
                	continue;
				}
                String schoolName = schoolService.getSchoolName(schoolCode);
                String[] paramsWeiXin = { "",  schoolName, teacherName, new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()), ""};
                paramsWeiXin[4] = teacherName + "老师提交了" + changeType + "申请，请及时处理！";
                // path参数为点击公众号消息后跳转的地址
                SendUtils.sendByWeixinAndPath(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId(), teacherInformationChange.getChangeType() == 0 ? "packageC/pages/teacher/teacherList" : "packageC/pages/teacher/teacherList?index=2");
            }
            // 提交后返回审核人员电话号码，前端非要传号码1，号码2的形式
			StringBuilder phoneStr = new StringBuilder();
			for (UserEntity userEntity : auditUserList) {
				phoneStr.append(",").append(userEntity.getMobile());
			}
			String phoneList = phoneStr.substring(1);
			return Msg.success().add("phoneList", phoneList);
        }
        return Msg.fail(ErrorEnum.E_101, ErrorEnum.E_101.getErrorMsg());
	}

    @ApiOperation(value = "管理员审核教师的信息修改/注册申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name="uid",value = "管理员id",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="changeId",value = "信息变更id",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name="agreed",value = "同意与否，2为同意，3为不同意",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name="changeType",value = "0为审核修改信息，1为审核新增信息",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name="roleIdList",value = "审核通过需要管理员赋予该教师角色",dataType = "Integer",paramType = "query", allowMultiple=true),
            @ApiImplicitParam(name="opinion",value = "审核意见",dataType = "String",paramType = "query"),
    })
    @PostMapping(value = "/teacher-info-change-check")
    public Msg checkParentInformationChange(String uid, Integer changeId, Integer agreed, Integer changeType, Integer[] roleIdList, String opinion){
        String permissionCode = "teacher-register:audit";
        boolean hasAuthorization = permissionService.hasAuthorization(uid, permissionCode);
        if (!hasAuthorization){
        	return Msg.fail(ErrorEnum.E_104, ErrorEnum.E_104.getErrorMsg());
		}

        // 判断该条记录是否已经审核过
		TeacherInformationChangeEntity teacherInformationChange = userService.listTeacherChangeRecord(changeId);
        if (teacherInformationChange.getAgreed() != 1){
        	return Msg.fail(ErrorEnum.E_101, "对不起，该条记录已经被审核过了，该次操作无效！");
		}
		// 查询该该条信息的变更/新增字段
        TeacherDetailInfoEntity changeInfo = userService.getTeacherInformationChangeDetail(changeId);
        // 角色可能有重复的需要去重
        HashSet<Integer> roleIdSet = new HashSet<>();
		roleIdSet.addAll(Arrays.asList(roleIdList));
        List<Role> roleList = new ArrayList<>();
		for (Integer roleId : roleIdSet) {
			Role role = roleService.findRoleByRoleId(roleId);
			roleList.add(role);
		}
		changeInfo.setRoleList(roleList);
        // 短信内容
        String content = "";
        // 根据通知的标志位判断是审核成功还是审核不通过
		String roleIds = null;
        if (agreed.equals(3)){
            if (changeType.equals(0)){
                content = "您在脸卡通智慧校园系统内的信息修改申请没有通过审核，请修改后重新提交。";
            }else if(changeType.equals(1)){
                content = "您在脸卡通智慧校园系统的注册申请没有通过审核，请修改后重新提交。";
            }
        }else if (agreed.equals(2)){
            if (changeType.equals(0)){
				// 审核通过，更新该教师的数据
				roleIds = userService.updateUser(changeInfo); //
                //  如果电话号码有修改，那么要解绑原手机号和当前教师使用微信的关系
                if (!StrUtils.isNullOrEmpty(changeInfo.getMobile())){
                    UserEntity userEntity = userService.getUserByUid(changeInfo.getId());
                    // 用就号码去查询他登录过小程序没有，登录过的话需要解绑
                    WeixinEntity weixinEntity = weixinService.getWeixinByPhone(userEntity.getMobile());
                    if (weixinEntity != null){
                        boolean cancelBindResult = parentService.weiXinBindNewPhone(weixinEntity.getId(), changeInfo.getMobile());
                        if (!cancelBindResult){
                            return Msg.fail(ErrorEnum.E_101, "微信号解绑失败！");
                        }
                    }
                }
                content = "您在脸卡通智慧校园系统内的信息修改申请已经通过审核！";
            } else if (changeType.equals(1)){
				// 审核通过，注册该教师的数据
				String registerTeacherId = "1" + System.currentTimeMillis();
				changeInfo.setId(registerTeacherId);
                roleIds = userService.insertUserByApply(changeInfo);
                content = "您在脸卡通智慧校园系统的注册申请已经通过审核！";
            }
        }
		// 审核后，更改该条申请记录的状态
		boolean result = userService.updateInfoChangeStatus(changeId, agreed, opinion, roleIds);
		// 然后短信通知教师信息修改审核是否通过，有新号码发送新号码，没有新号码发送给旧号码
		String mobile = changeInfo.getMobile();
		if (!StringUtils.isNoneBlank(mobile)){
			 mobile = userService.getUserByUid(changeInfo.getId()).getMobile();
		}
		if (mobile != null){
			if (StringUtils.isNoneBlank(opinion)){
				content = content + "审核意见：" + opinion;
			}
            sendToPerson(mobile, "200643", content);
        }
        return Msg.success();
    }

	@ApiOperation(value = "管理员查看教师列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid",value = "管理员id",dataType = "String",paramType = "query", required = true),
			@ApiImplicitParam(name="selectTeacherId",value = "要查询的人员id",dataType = "String",paramType = "query"),
	})
	@GetMapping(value = "/listTeacherInformation")
	public Msg listTeacherInformation(String uid, String selectTeacherId){
    	Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		// 查询教师基本信息（包括是否有信息修改记录）
		List<TeacherBasicInfoEntity> teacherList = userService.listTeacher(schoolCode, selectTeacherId, null);
		return Msg.success().add("teacherList", teacherList).add("showImage", showImage);
	}

	@ApiOperation(value = "管理员查看教师信息变更列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid",value = "管理员id",dataType = "String",paramType = "query", required = true),
			@ApiImplicitParam(name="changeType",value = "更改类型，0修改，1新增",dataType = "Integer",paramType = "query", required = true),
	})
	@GetMapping(value = "/listInfoChangeTeacher")
	public Msg listTeacherInformation(String uid, Integer changeType){
		Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		List<TeacherBasicInfoEntity> teacherList = new ArrayList<>();
		// 查询教师注册列表
		if (changeType.equals(1)){
			teacherList = userService.listRegisterTeacher(schoolCode, changeType, null);
		}
		return Msg.success().add("teacherList", teacherList).add("showImage", showImage);
	}

	@ApiOperation(value = "管理员查看教师信息变更记录详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid",value = "管理员id",dataType = "String",paramType = "query", required = true),
			@ApiImplicitParam(name="teacherInfoChangeId",value = "变更记录id",dataType = "Integer",paramType = "query", required = true),
	})
	@GetMapping(value = "/teacher-info-change-detail")
	public Msg teacherInfoChangeDetail(String uid, Integer teacherInfoChangeId){
		// 查询该条信息的变更/新增字段
		TeacherDetailInfoEntity teacherDetailInfo = userService.getTeacherInformationChangeDetail(teacherInfoChangeId);
		return Msg.success().add("changeInfo", teacherDetailInfo).add("showImage", showImage);
	}

	@ApiOperation(value = "是否有教师注册审核的权限---小程序端")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid",value = "用户",dataType = "String",paramType = "query", required = true),
	})
	@GetMapping(value = "/is-manager")
	public Msg isManager(String uid){
		// 教师注册审核的权限码
		String permissionCode = "teacher-register:audit";
		// 查找有教师注册审核权限的人员id
		Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		List<UserEntity> auditUserList = userService.listHasSomePermissionUserIdList(schoolCode, permissionCode);
		for (UserEntity userEntity : auditUserList) {
			if (userEntity.getId().equals(uid)){
				// 如果有权限，还要看该校有没有待审核的信息
				List<Integer> changeIds = userService.listChangeId(schoolCode);
				boolean hasCheck = false;
				if (changeIds.size() > 0){
					hasCheck = true;
				}
				return Msg.success().add("hasCheck", hasCheck);
			}
		}
		return Msg.fail(ErrorEnum.E_502, ErrorEnum.E_502.getErrorMsg());
	}

	@ApiOperation(value = "查询用户所在学校的职位列表，包括属于该职位的教师人数")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid",value = "用户id",dataType = "String",paramType = "query", required = true),
			@ApiImplicitParam(name="schoolCode",value = "学校id",dataType = "Integer",paramType = "query"),
	})
	@GetMapping(value = "/position-info")
	public Msg listPositionInfo(String uid, Integer schoolCode){
    	schoolCode = schoolCode == null ? userService.getSchoolCodeByUserId(uid) : schoolCode;
		List<TeacherPositionEntity> teacherPositionList = userService.listSchoolPosition(schoolCode);
		return Msg.success().add("teacherPositionList", teacherPositionList);
	}

	@ApiOperation(value = "查询属于某一职位的教师信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid",value = "用户id",dataType = "String",paramType = "query", required = true),
			@ApiImplicitParam(name="positionId",value = "职位id",dataType = "Integer",paramType = "query"),
	})
	@GetMapping(value = "/list-teacher-info-position")
	public Msg listTeacherInfoPosition(String uid, Integer positionId){
    	Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		List<TeacherBasicInfoEntity> teacherList = userService.listSchoolTeacherForPosition(schoolCode, positionId);
		return Msg.success().add("teacherList", teacherList).add("showImage", showImage);
	}

	@ApiOperation(value = "教师通讯录接口")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid",value = "用户id",dataType = "String",paramType = "query", required = true),
	})
	@GetMapping(value = "/list-teacher-contact")
	public Msg listTeacherContact(String uid){
    	Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		List<TeacherBasicInfoEntity> teacherList = userService.listTeacherContact(schoolCode);
		return Msg.success().add("teacherList", teacherList).add("showImage", showImage);
	}

	@ApiOperation(value = "多身份查询")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid", value = "用户id", dataType = "String", paramType = "query", required = true),
	})
	@GetMapping(value = "/list-identity")
	public Msg listUserIdentity(String uid){
		return listIdentity(uid);
	}

	@ApiOperation(value = "身份切换")
	@ApiImplicitParams({
			@ApiImplicitParam(name="uid", value = "用户id", dataType = "String", paramType = "query", required = true),
			@ApiImplicitParam(name="identityType", value = "要切换的身份（1教师，3家长）", dataType = "Integer", paramType = "query", required = true),
			@ApiImplicitParam(name="weiXinId", value = "微信id", dataType = "String", paramType = "query", required = true),
	})
	@PostMapping(value = "/change-identity")
	public Msg listUserIdentity(String uid, Integer identityType, String weiXinId){
    	// 切换前需要校验是否拥有多身份
		Msg msg = listIdentity(uid);
		List<com.alibaba.fastjson.JSONObject> userIdentityList = (List<com.alibaba.fastjson.JSONObject>)msg.getData().get("userIdentityList");
		if (userIdentityList == null || userIdentityList.size() < 2){
			return Msg.fail(ErrorEnum.E_101, "对不起，您没有多重身份，不能进行身份切换");
		}
		// 新增功能，前端可能会指定以哪种身份登录（1老师、3家长）
		if ((uid.startsWith("1") && identityType == 1) || (uid.startsWith("3") && identityType == 3)){
			return Msg.fail(ErrorEnum.E_101, "您已经是" + (identityType == 1 ? "教师" : "家长") + "身份，无需切换！");
		}
		String newUserId = "";
		if (identityType != null && identityType != 0){
			String phone;
			// 教师身份切换为家长身份
			if (identityType == 3){
				phone = userService.getUserByUid(uid).getMobile();
				newUserId = parentService.getParentByPhone(phone).getParentVisitorId();
			}else if (identityType == 1){	// 家长身份切换为教师身份
				phone = parentService.getparentById(uid).getParentVisitorPhone();
				newUserId = userService.getUserByMobile(phone).getId();
			}
			// 更新weixin_information表内uid
			weixinMapper.insertWeixinUid(weiXinId, newUserId);
		}
		return Msg.success().add("newUserId", newUserId).add("newUserType", identityType == 1 ? "teacher" : "parent");
	}

	/**
	 * 多身份查询
	 * @param uid
	 * @return
	 */
	private Msg listIdentity(String uid){
		String phone;
		if (uid.startsWith("1")){
			phone = userService.getUserByUid(uid).getMobile();
		}else if (uid.startsWith("3")){
			phone = parentService.getparentById(uid).getParentVisitorPhone();
		}else {
			return Msg.fail(ErrorEnum.E_101, "对不起，您的当前身份是访客，请重新关注公众号后登录小程序！");
		}
		List<String> userIdList = userService.listUserIdentity(phone);
		if (userIdList.size() > 2){
			logger.error("用户id" + uid + "信息有误！");
			return Msg.fail(ErrorEnum.E_101, "对不起，您的信息有误，请联系管理员！");
		}
		List<com.alibaba.fastjson.JSONObject> userIdentityList = new ArrayList<>();
		for (String userId : userIdList) {
			com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
			if (userId.startsWith("1")){
				jsonObject.put("identityType", 1);
				jsonObject.put("identityName", "教师");
			}else if (userId.startsWith("3")){
				jsonObject.put("identityType", 3);
				jsonObject.put("identityName", "家长");
			}
			userIdentityList.add(jsonObject);
		}
		return Msg.success().add("userIdentityList", userIdentityList);
	}


	// 短信发给审核进度给教师
	private void sendToPerson(String phone, String templateId,String paramString) {
		String[] paramsMobile = new String[2];
		paramsMobile[0] = paramString;
		//适配该家长通知的短信模板
		paramsMobile[1] = "";
		logger.info("短信发送给教师显示信息审核进度:" + phone);
		SendUtils.sendByShortMessage(phone, paramsMobile,templateId);
	}



}
